<template>
    <div class="content-box">
      <el-card class="card">
        <div class="box">
      <el-form  size="mini" inline ref="form" :rules="rules" label-width="150px"  :model="form" style="display: flex; flex-direction: column">
        <div class="settleIn-title" style="margin-top: 0">隐患标题：</div>
        <el-input type="text" size="mini" show-word-limit placeholder="请输入标题" clearable  maxlength="100" v-model="form.task_title"></el-input>
        <div class="settleIn-title">
          基本信息：
        </div>
        <div style="display: flex">
        <el-form-item label="隐患类型"
                      prop="type">
          <el-select style="width: 220px" v-model="form.type" placeholder="请选择隐患类型" @change="changeType">
            <el-option v-for="item in dangerTypeList"
                       :key="item"
                       :label="item"
                       :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="隐患领域"
                      prop="area">
          <el-select style="width: 220px" v-model="form.area" placeholder="请选择隐患领域" @change="changeArea">
            <el-option v-for="item in dangerAreaList"
                       :key="item"
                       :label="item"
                       :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="风险隐患等级"
                        prop="task_level"
          >
            <el-select style="width: 220px" v-model="form.task_level" placeholder="请选择风险隐患等级">
              <el-option v-for="item in levelList"
                         :key="item.id"
                         :label="item.label"
                         :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: flex">
        <el-form-item label="检查时间"
                      prop="task_inspection_time"
        >
          <el-date-picker
              v-model="form.task_inspection_time"
              value-format="yyyy-MM-dd"
              align="right"
              type="date"
              placeholder="请输入检查时间"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="规定整改完成时间"
                      prop="task_anticipate_time"
        >
          <el-date-picker
              v-model="form.task_anticipate_time"
              value-format="yyyy-MM-dd"
              align="right"
              type="date"
              placeholder="请输入规定整改完成时间"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
          <el-form-item label="责任部门" prop="task_dept">
            <el-select style="width: 220px" v-model="form.task_dept" placeholder="请选择部门">
              <el-option v-for="item in deptList"
                         :key="item"
                         :label="item"
                         :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: flex">
        </div>
        <div class="settleIn-title">场所或施工项目名称:</div>
          <el-input type="text" size="mini"  show-word-limit placeholder="请输入场所或施工项目名称" clearable  maxlength="100" v-model="form.task_name"></el-input>
        <div class="settleIn-title">问题及隐患详情:</div>
          <el-input  :rows="3" size="mini" type="textarea" show-word-limit v-model="form.task_content" clearable placeholder="请输入问题及隐患详情" ></el-input>
          <div class="settleIn-title">整改照片：</div>
          <el-upload
              action=""
              ref="uploadImg1"
              list-type="picture-card"
              v-loading="uploading1"
              :auto-upload="false"
              :file-list="fileList1"
              :before-upload="beforeAvatarUpload1"
              :on-preview="handlePreview1"
              :on-remove="handleRemove1"
              :on-change="handleFileChange1"
              :before-remove="beforeRemove1"
              :class="{disabled:uploadDisabled1}"
              :limit="15"
              :on-exceed="handleExceed1"
          >
            <span :class="{disabled:uploadDisabled1}">
                <i  class="el-icon-plus"></i>
              </span>
            <div slot="tip" style="color: orangered;font-size: 10px;margin: 5px 0">只能上传jpg/png文件，</div>
            <div slot="tip" style="color: orangered;font-size: 10px">且单张不超过2MB</div>
          </el-upload>
          <el-dialog :visible.sync="dialogImgVisible1">
            <img width="100%" :src="dialogImageUrl1" alt="图片未找到">
          </el-dialog>
      </el-form>
      <div>
      <el-button  @click="cancel" class="btn" size="mini">取消</el-button>
      <el-button style="margin-left: 3em" class="btn"  type="primary" @click="submit" size="mini">提交</el-button>
      </div>
        </div>
      </el-card>
    </div>
</template>
<script>
import {dangerType,dangerArea} from '@/api/dangertypes'
import {deptInfo} from "@/api/dept";
import {taskAdd} from "@/api/task";
export default {
  name: 'WorkOrderRelease',
  data() {
    return {
      index:'',
      uploading1:false,
      uploadDisabled1: false,
      dialogImgVisible1:false,
      dialogImageUrl1:'',
      fileList1: [],
      dangerTypeList:[],
      dangerAreaList:[],
      levelList:[
        {
          id:1,
          value:'重大',
          label:'重大'
        },
        {
          id:2,
          value:'一般',
          label:'一般'
        }
      ],
      deptList:[],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      form: {
        type: '',
        area: '',
        task_title:'',
        images_before:[],
        task_anticipate_time:'',
        task_level:'',
        task_content:'',
        task_name:'',
        task_inspection_time:'',
        task_type:'',
        task_dept:'',
      },
      dangerArray:[],
      rules: {
        type: [
          {
            required: true,
            message: '请输入隐患类型',
            trigger:'blur'
          }
        ],
        area: [
          {
            required: true,
            message: '请输入隐患领域',
            trigger:'blur'
          }
        ],
        task_title:[
          {
            required: true,
            message: '请输入隐患标题',
            trigger:'blur'
          }
        ],
        task_inspection_time:[
          {
            required: true,
            message: '请选择检查时间',
            trigger:'blur'
          }
        ],
        task_anticipate_time:[
          {
            required: true,
            message: '请选择规定整改完成时间',
            trigger:'blur'
          }
        ],
        task_level:[
          {
            required: true,
            message: '请选择风险隐患等级',
            trigger:'blur'
          }
        ],
        task_content:[
          {
            required: true,
            message: '请输入问题及隐患详情',
            trigger:'blur'
          }
        ],
        task_name:[
          {
            required: true,
            message: '请输入场所或施工项目名称',
            trigger:'blur'
          }
        ],
        task_dept:[
          {
            required: true,
            message: '请选择责任部门',
            trigger:'blur'
          }
        ],
        images_before:[
          {
            required: true,
            message: '请至少上传一张图片'
          }
        ]
      },
      tableData: []
    }
  },
  mounted() {
    this.created();
  },
  methods: {
    created() {
      let _this = this;
      deptInfo({}).then(resp=>{
        if(resp.code===1){
          let params = {
            page_number: 1,
            page_size:resp.total_count,
            status: true
          }
          deptInfo(params).then(res=>{
            let temp = res.data
            for(let i = 0;i<temp.length;i++){
              _this.deptList = [..._this.deptList,temp[i].deptname]
            }
            console.log(_this.deptList)
          })

        }
      })
      dangerType({}).then(res=>{
        if(res.code === 1){
          _this.dangerTypeList = res.data
        }
      })
    },
    changeType(){
      this.dangerArray = []
      this.dangerAreaList = []
      let params = {
        type:this.form.type,
        area:'',
        status:1
      }
      dangerArea(params).then(res=>{
        if(res.code === 1){
          this.dangerArray = res.data
          for(let i = 0;i<this.dangerArray.length;i++){
            this.dangerAreaList = [...this.dangerAreaList,this.dangerArray[i].area]
          }
        }
      })
    },
    changeArea(){
      this.form.task_type = ''
      let dangerObject = this.dangerArray.filter(ele=>((ele.type === this.form.type)&&(ele.area === this.form.area)))
      console.log(dangerObject)
      this.form.task_type = dangerObject[0].id
      console.log(this.form.task_type)
    },
    cancel(){
      this.$refs.uploadImg1.clearFiles()
      this.fileList1.length=0
      this.uploadDisabled1=(this.fileList1.length>=3)
      this.$refs.form.resetFields()
      this.form = {}
    },
    submit(){
      this.$refs.form.validate((valid) => {
        if(valid) {
          delete this.form.type
          delete this.form.area
          console.log(this.form)
          taskAdd(this.form).then(res=>{
            if(res.code === 1){
              this.$message.success(res.task_id+'号'+res.message)
              this.cancel()
              this.$router.push('/workorderaudit')
            }
          })
        }
      })
    },
    handleFileChange1(file,fileList){
      this.uploadDisabled1=(fileList.length>=3)
      this.fileList1 = fileList
      console.log(file,fileList)
      console.log(this.fileList1)
      const imgType = file.raw.type === 'image/jpeg'|| file.raw.type === 'image/png'
      const isLt2MB = file.size / 1024 / 1024 < 2;
      if (!imgType) {
        this.$message.error("上传图片只能是 JPG和png 格式!");
        this.uploadDisabled1=(fileList.length>=3)
        console.log(fileList)
        return false
      }
      if(!file.raw){
        this.$message.error("选择图片错误！")
      }
      if (!isLt2MB) {
        this.uploading1=true
        this.$message.success("图片大小超过2MB，正在压缩中...");
        setTimeout(() => {
          //代码
          this.uploading1=false
        }, 2000);
        let that = this;
        let reader = new FileReader();
        // 将图片将转成 base64 格式
        reader.readAsDataURL(file.raw);
        reader.onloadend = function () {
          let result = this.result;
          console.log(result)
          let img = new Image();
          img.src = result;
          // compressImg.src = file.url;
          console.log(img.src)
          img.onload = function (){
            let maxWidth = 800;
            let maxHeight = 800;
            let originWidth = img.width; //图片原始宽
            let originHeight = img.height; //图片原始高
            // console.log(originWidth)
            // console.log(originHeight)
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d')
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }
            canvas.width = targetWidth
            canvas.height = targetHeight
            // 图片压缩
            ctx.drawImage(img, 0, 0, targetWidth, targetHeight)
            // canvas对图片进行缩放 0.3是我定义的图片质量，
            let base64 = canvas.toDataURL(file.raw.type, 0.3);
            console.log(base64)
            //将base64转换为file流
            let Compressfile= that.convertBase64UrlToFile({
              dataURL: base64,
              type: file.raw.type,
              contentName: file.name
            })
            console.log('压缩后', Compressfile)
            file = {
              id: "compress1",//标记图片的唯一性，可按自己方式定义
              url:Compressfile.path,
              file: Compressfile
            };
            setTimeout(function(){
              that.$message.success('已压缩至2MB以下')
            },2000)
            that.form.images_before.push(base64)
            console.log(result.length) //result是返回图片base64格式
            console.log(that.form.images_before.length)
            console.log(img.width)
            console.log(img.height)
            console.log(Compressfile)
            console.log(file,fileList)
            console.log(that.form.images_before)
            console.log(that.form.images_before[0])
            console.log(that.form.images_before[1])
            console.log(that.form.images_before[2])
            console.log(that.form.images_before[3])
            console.log(that.form.images_before[4])
            console.log(that.form.images_before[5])
            console.log(that.form.images_before[6])
            console.log(that.form.images_before[7])
            console.log(that.form.images_before[8])
            console.log(that.form.images_before[9])
            console.log(that.form.images_before[10])
            console.log(that.form.images_before[11])
            console.log(that.form.images_before[12])
            console.log(that.form.images_before[13])
            console.log(that.form.images_before[14])
          }
        }
      } else {
        //这里写直接上传 转base64
        const self = this;
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function (e) {
          let img_base64 = e.target.result;
          self.form.images_before.push(img_base64)
          console.log(self.form.images_before)
        }
      }
    },
    convertBase64UrlToFile(base64) {
      let urlData = base64.dataURL
      let type = base64.type
      let contentName = base64.contentName
      let bytes = null
      if (urlData.split(',').length > 1) { //是否带前缀
        bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
      } else {
        bytes = window.atob(urlData)
      }
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length)
      let ia = new Uint8Array(ab)
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      let result = new Blob([ab], {
        type: type,
      })
      let result1 = new File([result], contentName, {
        type: type
      })
      result1.path = window.URL.createObjectURL(result)
      return result1
    },
    handleExceed1() {
      this.$message.warning(`只能上传十五张图片`);
    },
    beforeRemove1(file,fileList) {
      this.index = fileList.indexOf(file)
      console.log('index',this.index)
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload1(file){
      console.log(file)
    },
    handleRemove1(file, fileList) {
      console.log(file, fileList);
      this.uploadDisabled1=(fileList.length>=15)
      this.form.images_before.splice(this.index,1)
      console.log(this.form.images_before)
    },
    handlePreview1(file) {
      console.log(file.size);
      // window.open(file.url)
      this.dialogImageUrl1 = file.url;
      this.dialogImgVisible1 = true;
      this.uploadDisabled1 = true
    }
  }
}
</script>
<style lang="scss" scoped>
  .content-box {
    .card{
      //height: 625px;
      .box{
        display: flex;
        flex-direction: column;
        background-color: #fff;
        height:80vh;
        //height:100vh;
        //height: 50%;
        overflow:auto;
        .settleIn-title {
          letter-spacing: 1px;
          font-size: 17px;
          font-weight: bold;
          margin: 20px 0;
        }
      }
    }
  }
  .btn {
    margin-top: 2em;
  }

::v-deep.el-form-item__label {
  font-size: 16px;
}

::v-deep .el-form-item {
    width: 33.3%;
  }

</style>